import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '_views/Home'
import { isLogin } from '_utils'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: '首页',
    meta: {
      needLogin: false
    },
    component: Home
  },
  {
    path: '/cate',
    name: '分类',
    meta: {
      needLogin: false
    },
    component: () => import('_views/Cate')
  },
  {
    path: '/cart',
    name: '购物车',
    meta: {
      needLogin: true
    },
    component: () => import('_views/Cart')
  },
  {
    path: '/user',
    name: '我的',
    meta: {
      needLogin: true
    },
    component: () => import('_views/User')
  },
  {
    path: '/detail',
    name: '商品详情',
    meta: {
      needLogin: false
    },
    component: () => import('_views/Detail')
  },
  {
    path: '/itemlist',
    name: '商品列表',
    meta: {
      needLogin: false
    },
    component: () => import('_views/ItemList')
  },
  {
    path: '/login',
    name: '登录',
    meta: {
      needLogin: false
    },
    component: () => import('_views/Login')
  },
  {
    path: '/register',
    name: '注册',
    meta: {
      needLogin: false
    },
    component: () => import('_views/Register')
  },
  {
    path: '/search',
    name: '搜索',
    meta: {
      needLogin: false
    },
    component: () => import('_views/Search')
  },
  {
    path: '/searchresult',
    name: '搜索结果页',
    meta: {
      needLogin: false
    },
    component: () => import('_views/SearchResult')
  },
  {
    path: '/ordercreate',
    name: '订单页',
    meta: {
      needLogin: true
    },
    component: () => import('_views/OrderCreate')
  },
  {
    path: '/contactlists',
    name: '联系人页',
    meta: {
      needLogin: true
    },
    component: () => import('_views/ContactLists')
  },
  {
    path: '/contactupdate',
    name: '联系人编辑',
    meta: {
      needLogin: true
    },
    component: () => import('_views/ContactUpdate')
  },
  {
    path: '/contactadd',
    name: '联系人新增',
    meta: {
      needLogin: true
    },
    component: () => import('_views/ContactAdd')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
router.beforeEach((to, from, next) => {
  if (to.meta.needLogin) {
    // 需要登录
    if (isLogin()) {
      // 登录了
      next()
    } else {
      // 没有登录
      next({
        path: '/login',
        query: {
          from: to.path
        }
      })
    }
  } else {
    next()
  }
})
export default router
